package com.shigui.news.controller.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.shigui.news.controller.BaseAction;
import com.shigui.news.enums.ResponseCode;
import com.shigui.news.exception.NewsException;
import com.shigui.news.interceptor.JsonFormat;
import com.shigui.news.model.Category;
import com.shigui.news.model.News;
import com.shigui.news.model.User;
import com.shigui.news.service.CategoryService;
import com.shigui.news.service.NewsService;
import com.shigui.news.utils.MD5;

/**
 * action层
 * curd
 * @author Shiguiwu
 *
 */
@Scope("prototype")
@Controller("newsAction")
public class NewsAction extends BaseAction {
	@Autowired
	private NewsService newsService;
	
	@Autowired
	private CategoryService categoryService;
	
	private Category category;
	
	private News news;
	
	private InputStream attachment;
	private String attachmentName;
	/*
	 	select * from t_user;
	 	select * from t_comment;
	 	select * from news;
	 	select * from category;
	 */

	
	
	public void selectById(){
		
		News enN = newsService.selectById(news.getNewsId());
		
		if(enN == null){
			
			throw new NewsException(ResponseCode.NEWS_FIND);
		}
//		enN.setTitle(news.getTitle());
//		enN.setContent(news.getContent());
//		enN.setCreateTime(news.getCreateTime());
//		enN.setAuthor(news.getAuthor());
		enN.setNum(enN.getNum()+N);
//		enN.setCateId(news.getCateId());
//		enN.setNewsId(news.getNewsId());
		
		newsService.updateNum(enN);
		
		getHttpRequest().setAttribute(JsonFormat.RESPONSE_MESSAGE_KEY,"点击次数：  "+ enN.getNum());
		getHttpRequest().setAttribute(JsonFormat.RESPONSE_DATE_KEY, enN);
		
	
		
	}
	public void delete(){
		
		User userLogin = findByPersistCodeOrFail();
		
		News ne = newsService.selectById(news.getNewsId());
		
		newsService.delete(userLogin,ne);
		
		/**
		 *格式化结构 
		 */
		getHttpRequest().setAttribute(JsonFormat.RESPONSE_DATE_KEY, news);
		
		
		
		
	}
	public void add(){
		
		User userLogin = findByPersistCodeOrFail();
		
		newsService.insert(userLogin, news);
		
		getHttpRequest().setAttribute(JsonFormat.RESPONSE_DATE_KEY, news);
		
		
	}
	public void update(){
		
		
		News enN = newsService.selectById(news.getNewsId());
		
		enN.setTitle(news.getTitle());
		
		newsService.update(enN);
		
		getHttpRequest().setAttribute(JsonFormat.RESPONSE_DATE_KEY, news);
		
		
	}
	/**
	 * 每查找一次，点击更新1++
	 * 次函数用在查找里
	 */
	public void updateNum(){
		
		News enN = newsService.selectById(news.getNewsId());
		
		if(enN == null){
			
			throw new NewsException(ResponseCode.NEWS_UPDATE);
		}
		
		enN.setNum(news.getNum()+N);
		
		newsService.updateNum(enN);
		
		getHttpRequest().setAttribute(JsonFormat.RESPONSE_MESSAGE_KEY, enN.getNum());
		getHttpRequest().setAttribute(JsonFormat.RESPONSE_DATE_KEY, enN);
		
		
	}
	/**
	 * 分页
	 * @return
	 */
	public void getNewsList(){
		
		
		Category cate=categoryService.selectById(category.getCateId());
		
		setTotal(newsService.getCountNews(cate));
		
		List<News> newsesList = newsService.getNewsList( cate, getPage(), getCount());
		
		/**
		 * 格式化返回结果
		 */
		ArrayList<News> tmp = new ArrayList<News>();
		
		for(News news : newsesList){
			
			News n = new News();
			
			n.setNewsId(news.getNewsId());
			n.setTitle(news.getTitle());
			n.setAuthor(news.getAuthor());
			n.setNum(news.getNum());
			
			tmp.add(n);
			
		}
		System.out.println("b + b = 2b");
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("page", getPage());
		map.put("count", getCount());
		map.put("total", getTotal());
		System.out.println("a + a = aa");
		map.put("data", tmp);
		
		System.out.println("1+1 = 2 ");
		
		getHttpRequest().setAttribute(JsonFormat.RESPONSE_DATE_KEY, map);
		
	}
	
	protected String uploadFile() throws Exception{
		
		String originFileName = news.getAttachmentFileName();
		
		String suffix = originFileName.substring(originFileName.indexOf("."), originFileName.length());
		/**
		 * 生成随机的文件名
		 */
		String fileName = N.toString() + "_" 
				+ MD5.encode(news.getTitle() + System.currentTimeMillis())
				+ suffix;
		/**
		 * 生成文件保存的路径
		 * 
		 * 
		 */
		String uploadPath = ServletActionContext.getServletContext()
					.getRealPath("/WEB-INF/upload");
		/**
		 * 创建文件，构造为路径和文件名
		 */
		File targetFile = new File(uploadPath, fileName);
		
		/**
		 * 上传的文件是存储在临时目录，操作系统会不定时清除，需要将文件移动到其他位置，持久化存储
		 * 读取上传的文件内容，并写入到targetFile，存储在硬盘上
		 */
		FileUtils.copyFile(news.getAttachment(), targetFile);
		
		/**
		 * 返回路径
		 */
		return targetFile.getAbsolutePath();
		
	}
	/**
	 * 下载附件
	 * @return
	 */
	
	public String downloadAttachment(){
		
		User loginUser = findByPersistCodeOrFail();
		
		News news = newsService. selectById(this.news.getNewsId());
		/**
		 * 找不到的话跑一圈
		 */
		if(news == null){
			
			throw new NewsException(ResponseCode.NEWS_FIND);
		}
		
		try {
			FileInputStream attachment = new FileInputStream(new File(news.getAttachmentPath()));
			
			this.setAttachment(attachment);
			
			this.setAttachmentName("filename-manual-set");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return SUCCESS;
	}
	
	

	public News getNews() {
		return news;
	}
	public void setNews(News news) {
		this.news = news;
	}
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	public InputStream getAttachment() {
		return attachment;
	}
	public void setAttachment(InputStream attachment) {
		this.attachment = attachment;
	}
	public String getAttachmentName() {
		return attachmentName;
	}
	public void setAttachmentName(String attachmentName) {
		this.attachmentName = attachmentName;
	}
	
	
	

}
